package auth

import (
	"context"
	"fast-boot/app/model"
	"fast-boot/common/xerr"
	"github.com/hwUltra/fb-tools/jwtx"
	"github.com/hwUltra/fb-tools/sms"
	"time"

	"fast-boot/app/api/wxapp/internal/svc"
	"fast-boot/app/api/wxapp/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (*types.LoginResp, error) {
	var smsClient = sms.NewVCode(l.svcCtx.Config.Sms, l.svcCtx.Config.Cache)
	if err := smsClient.Check(l.svcCtx.Config.Sms.Template["Reg"], req.Mobile, req.Vcode); err != nil {
		return nil, err
	}
	user := model.UserModel{}
	if err := l.svcCtx.GormClient.GormDb.First(&user, "mobile=?", req.Mobile).Error; err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, xerr.NewErrMsg("用户不存在")
	}

	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	accessToken, err := jwtx.NewJwtX(l.ctx, l.svcCtx.Config.JwtUserKey).GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, user.Id)
	if err != nil {
		return nil, err
	}
	resp := &types.LoginResp{
		AccessToken:  accessToken,
		RefreshAfter: now + accessExpire,
		AccessExpire: now + accessExpire/2,
	}

	return resp, nil
}
